﻿#ifndef ___PCLIB_S_MD5___
#define ___PCLIB_S_MD5___


#include "../m_core/m_core.hpp"
#include "s_crypto_base.hpp"

#define PCMD5_LEN    (16)

/**
*@brief        MD5计算
*/
class CPCMD5 :CPCNoCopyable
{
public:
    explicit CPCMD5(){ Init(); }

    /**
    *@brief     直接获取字节或字符串的md5
    *@param     szSrc   [in]    输入的数据
    *@param     nLen    [in]    输入的数据长度
    *@return    16字节的md5
    */
    static const std::string GetBytesMD5(const void *src, size_t len)
    {
        CPCMD5 md5;
        md5.Update(src, len);
        return md5.Finish();
    }

    /**
    *@brief     直接获取字节或字符串的md5 hmac
    *@param     src[in]         输入的数据
    *@param     srclen[in]      数据长度
    *@param     keybytes[in]    密钥
    *@param     keylen[in]      密钥长度
    *@return    16字节的md5 hmac
    */
    static std::string GetBytesMD5HMAC(const void *src, size_t srclen,const void *keybytes, size_t keylen)
    {
        return PCGetBytesHMAC<CPCMD5>(src,srclen,keybytes,keylen,64,PCMD5_LEN);
    }

    /**
    *@brief     直接获取字节或字符串的md5
    *@param     szSrc   [in]    输入的数据
    *@param     nLen    [in]    输入的数据长度。nLen < 0 时，认为szSrc为c字符串。
    *@return    32个字符的可见md5，失败为空
    */
    static const std::string GetBytesMD5Hex(const void *szSrc, int nLen = -1)
    {
        //参数检查
        size_t nLenReal;
        if (nLen < 0)   nLenReal = szSrc?strlen((char*)szSrc):0;
        else            nLenReal = (size_t)nLen;

        auto bytes = GetBytesMD5(szSrc, nLenReal);
        return CPCStrUtil::PCBytes2Dsp(bytes.data(), bytes.length(), "", true);
    }

    /**
    *@brief     获取文件md5函数
    *@param     pszPath    [in]  文件路径
    *@return    是否成功。成功时std::string为结果的十六进制可见字符串
    */
    static CPCResult<std::string> PCGetFileMD5Hex(const char* pszPath)
    {
        return PCGetFileHashHex<CPCMD5>(pszPath);
    };

public:

    //初始化
    void Init()
    {
        /* reset number of bits. */
        _count[0] = _count[1] = 0;
        /* Load magic initialization constants. */
        _state[0] = 0x67452301;
        _state[1] = 0xefcdab89;
        _state[2] = 0x98badcfe;
        _state[3] = 0x10325476;
    }

    //执行一次计算，可以重复调用
    void Update(const void *src, size_t length)
    {
        const unsigned char * input = (const unsigned char *)(src?src:"");
        unsigned int i, index, partLen;

        /* Compute number of bytes mod 64 */
        index = (unsigned int)((_count[0] >> 3) & 0x3f);

        /* update number of bits */
        if ((_count[0] += ((unsigned int)length << 3)) < ((unsigned int)length << 3))
            _count[1]++;
        _count[1] += ((unsigned int)length >> 29);

        partLen = 64 - index;

        /* transform as many times as possible. */
        if (length >= partLen)
        {
            memcpy(&_buffer[index], input, partLen);
            PCMD5_transform(_buffer);

            for (i = partLen; i + 63 < length; i += 64)
                PCMD5_transform(&input[i]);
            index = 0;
        }
        else
        {
            i = 0;
        }

        /* Buffer remaining input */
        memcpy(&_buffer[index], &input[i], length - i);
    }

    //获取执行结果，结果固定为16字节 PCMD5_LEN
    std::string Finish()
    {
        unsigned char bits[8];
        unsigned int oldState[4];
        unsigned int oldCount[2];
        unsigned int index, padLen;

        /* Save current state and count. */
        memcpy(oldState, _state, 16);
        memcpy(oldCount, _count, 8);

        /* Save number of bits */
        PCMD5_encode(_count, bits, 8);

        /* Pad out to 56 mod 64. */
        index = (unsigned int)((_count[0] >> 3) & 0x3f);
        padLen = (index < 56) ? (56 - index) : (120 - index);

        static const unsigned char PADDING[64] = { 0x80 };
        Update(PADDING, padLen);

        /* Append length (before padding) */
        Update(bits, 8);

        /* Store state in digest */
        unsigned char _digest[PCMD5_LEN];  
        PCMD5_encode(_state, _digest, PCMD5_LEN);

        /* Restore current state and count. */
        memcpy(_state, oldState, 16);
        memcpy(_count, oldCount, 8);
        return std::string((const char*)_digest,PCMD5_LEN);
    }

protected:
    /* MD5 basic transformation. Transforms _state based on block. */
    void PCMD5_transform(const unsigned char block[64])
    {
        //////////////////////////////////////////////////////////////////
        #define PCMD5_S11 7 
        #define PCMD5_S12 12 
        #define PCMD5_S13 17 
        #define PCMD5_S14 22 
        #define PCMD5_S21 5 
        #define PCMD5_S22 9 
        #define PCMD5_S23 14 
        #define PCMD5_S24 20 
        #define PCMD5_S31 4 
        #define PCMD5_S32 11 
        #define PCMD5_S33 16 
        #define PCMD5_S34 23 
        #define PCMD5_S41 6 
        #define PCMD5_S42 10 
        #define PCMD5_S43 15 
        #define PCMD5_S44 21 

        #define PCMD5F(x, y, z) (((x) & (y)) | ((~x) & (z))) 
        #define PCMD5G(x, y, z) (((x) & (z)) | ((y) & (~z))) 
        #define PCMD5H(x, y, z) ((x) ^ (y) ^ (z)) 
        #define PCMD5I(x, y, z) ((y) ^ ((x) | (~z))) 

        #define PCMD5ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n)))) 

        #define PCMD5FF(a, b, c, d, x, s, ac) { (a) += PCMD5F ((b), (c), (d)) + (x) + ac; \
              (a) = PCMD5ROTATE_LEFT ((a), (s)); \
              (a) += (b); \
            } 
        #define PCMD5GG(a, b, c, d, x, s, ac) { \
              (a) += PCMD5G ((b), (c), (d)) + (x) + ac; \
              (a) =  PCMD5ROTATE_LEFT ((a), (s)); \
              (a) += (b); \
            } 
        #define PCMD5HH(a, b, c, d, x, s, ac) { \
              (a) += PCMD5H ((b), (c), (d)) + (x) + ac; \
              (a) =  PCMD5ROTATE_LEFT ((a), (s)); \
              (a) += (b); \
            } 
        #define PCMD5II(a, b, c, d, x, s, ac) { \
              (a) += PCMD5I ((b), (c), (d)) + (x) + ac; \
              (a) =  PCMD5ROTATE_LEFT ((a), (s)); \
              (a) += (b); \
            } 
        //////////////////////////////////////////////////////////////////
        unsigned int a = _state[0], b = _state[1], c = _state[2], d = _state[3], x[16];

        PCMD5_decode(block, x, 64);

        /* Round 1 */
        PCMD5FF(a, b, c, d, x[0], PCMD5_S11, 0xd76aa478); /* 1 */
        PCMD5FF(d, a, b, c, x[1], PCMD5_S12, 0xe8c7b756); /* 2 */
        PCMD5FF(c, d, a, b, x[2], PCMD5_S13, 0x242070db); /* 3 */
        PCMD5FF(b, c, d, a, x[3], PCMD5_S14, 0xc1bdceee); /* 4 */
        PCMD5FF(a, b, c, d, x[4], PCMD5_S11, 0xf57c0faf); /* 5 */
        PCMD5FF(d, a, b, c, x[5], PCMD5_S12, 0x4787c62a); /* 6 */
        PCMD5FF(c, d, a, b, x[6], PCMD5_S13, 0xa8304613); /* 7 */
        PCMD5FF(b, c, d, a, x[7], PCMD5_S14, 0xfd469501); /* 8 */
        PCMD5FF(a, b, c, d, x[8], PCMD5_S11, 0x698098d8); /* 9 */
        PCMD5FF(d, a, b, c, x[9], PCMD5_S12, 0x8b44f7af); /* 10 */
        PCMD5FF(c, d, a, b, x[10], PCMD5_S13, 0xffff5bb1); /* 11 */
        PCMD5FF(b, c, d, a, x[11], PCMD5_S14, 0x895cd7be); /* 12 */
        PCMD5FF(a, b, c, d, x[12], PCMD5_S11, 0x6b901122); /* 13 */
        PCMD5FF(d, a, b, c, x[13], PCMD5_S12, 0xfd987193); /* 14 */
        PCMD5FF(c, d, a, b, x[14], PCMD5_S13, 0xa679438e); /* 15 */
        PCMD5FF(b, c, d, a, x[15], PCMD5_S14, 0x49b40821); /* 16 */

        /* Round 2 */
        PCMD5GG(a, b, c, d, x[1], PCMD5_S21, 0xf61e2562); /* 17 */
        PCMD5GG(d, a, b, c, x[6], PCMD5_S22, 0xc040b340); /* 18 */
        PCMD5GG(c, d, a, b, x[11], PCMD5_S23, 0x265e5a51); /* 19 */
        PCMD5GG(b, c, d, a, x[0], PCMD5_S24, 0xe9b6c7aa); /* 20 */
        PCMD5GG(a, b, c, d, x[5], PCMD5_S21, 0xd62f105d); /* 21 */
        PCMD5GG(d, a, b, c, x[10], PCMD5_S22, 0x2441453); /* 22 */
        PCMD5GG(c, d, a, b, x[15], PCMD5_S23, 0xd8a1e681); /* 23 */
        PCMD5GG(b, c, d, a, x[4], PCMD5_S24, 0xe7d3fbc8); /* 24 */
        PCMD5GG(a, b, c, d, x[9], PCMD5_S21, 0x21e1cde6); /* 25 */
        PCMD5GG(d, a, b, c, x[14], PCMD5_S22, 0xc33707d6); /* 26 */
        PCMD5GG(c, d, a, b, x[3], PCMD5_S23, 0xf4d50d87); /* 27 */
        PCMD5GG(b, c, d, a, x[8], PCMD5_S24, 0x455a14ed); /* 28 */
        PCMD5GG(a, b, c, d, x[13], PCMD5_S21, 0xa9e3e905); /* 29 */
        PCMD5GG(d, a, b, c, x[2], PCMD5_S22, 0xfcefa3f8); /* 30 */
        PCMD5GG(c, d, a, b, x[7], PCMD5_S23, 0x676f02d9); /* 31 */
        PCMD5GG(b, c, d, a, x[12], PCMD5_S24, 0x8d2a4c8a); /* 32 */

        /* Round 3 */
        PCMD5HH(a, b, c, d, x[5], PCMD5_S31, 0xfffa3942); /* 33 */
        PCMD5HH(d, a, b, c, x[8], PCMD5_S32, 0x8771f681); /* 34 */
        PCMD5HH(c, d, a, b, x[11], PCMD5_S33, 0x6d9d6122); /* 35 */
        PCMD5HH(b, c, d, a, x[14], PCMD5_S34, 0xfde5380c); /* 36 */
        PCMD5HH(a, b, c, d, x[1], PCMD5_S31, 0xa4beea44); /* 37 */
        PCMD5HH(d, a, b, c, x[4], PCMD5_S32, 0x4bdecfa9); /* 38 */
        PCMD5HH(c, d, a, b, x[7], PCMD5_S33, 0xf6bb4b60); /* 39 */
        PCMD5HH(b, c, d, a, x[10], PCMD5_S34, 0xbebfbc70); /* 40 */
        PCMD5HH(a, b, c, d, x[13], PCMD5_S31, 0x289b7ec6); /* 41 */
        PCMD5HH(d, a, b, c, x[0], PCMD5_S32, 0xeaa127fa); /* 42 */
        PCMD5HH(c, d, a, b, x[3], PCMD5_S33, 0xd4ef3085); /* 43 */
        PCMD5HH(b, c, d, a, x[6], PCMD5_S34, 0x4881d05); /* 44 */
        PCMD5HH(a, b, c, d, x[9], PCMD5_S31, 0xd9d4d039); /* 45 */
        PCMD5HH(d, a, b, c, x[12], PCMD5_S32, 0xe6db99e5); /* 46 */
        PCMD5HH(c, d, a, b, x[15], PCMD5_S33, 0x1fa27cf8); /* 47 */
        PCMD5HH(b, c, d, a, x[2], PCMD5_S34, 0xc4ac5665); /* 48 */

        /* Round 4 */
        PCMD5II(a, b, c, d, x[0], PCMD5_S41, 0xf4292244); /* 49 */
        PCMD5II(d, a, b, c, x[7], PCMD5_S42, 0x432aff97); /* 50 */
        PCMD5II(c, d, a, b, x[14], PCMD5_S43, 0xab9423a7); /* 51 */
        PCMD5II(b, c, d, a, x[5], PCMD5_S44, 0xfc93a039); /* 52 */
        PCMD5II(a, b, c, d, x[12], PCMD5_S41, 0x655b59c3); /* 53 */
        PCMD5II(d, a, b, c, x[3], PCMD5_S42, 0x8f0ccc92); /* 54 */
        PCMD5II(c, d, a, b, x[10], PCMD5_S43, 0xffeff47d); /* 55 */
        PCMD5II(b, c, d, a, x[1], PCMD5_S44, 0x85845dd1); /* 56 */
        PCMD5II(a, b, c, d, x[8], PCMD5_S41, 0x6fa87e4f); /* 57 */
        PCMD5II(d, a, b, c, x[15], PCMD5_S42, 0xfe2ce6e0); /* 58 */
        PCMD5II(c, d, a, b, x[6], PCMD5_S43, 0xa3014314); /* 59 */
        PCMD5II(b, c, d, a, x[13], PCMD5_S44, 0x4e0811a1); /* 60 */
        PCMD5II(a, b, c, d, x[4], PCMD5_S41, 0xf7537e82); /* 61 */
        PCMD5II(d, a, b, c, x[11], PCMD5_S42, 0xbd3af235); /* 62 */
        PCMD5II(c, d, a, b, x[2], PCMD5_S43, 0x2ad7d2bb); /* 63 */
        PCMD5II(b, c, d, a, x[9], PCMD5_S44, 0xeb86d391); /* 64 */

        _state[0] += a;
        _state[1] += b;
        _state[2] += c;
        _state[3] += d;
        //////////////////////////////////////////////////////////////////
        #undef PCMD5_S11
        #undef PCMD5_S12
        #undef PCMD5_S13
        #undef PCMD5_S14
        #undef PCMD5_S21
        #undef PCMD5_S22
        #undef PCMD5_S23
        #undef PCMD5_S24
        #undef PCMD5_S31
        #undef PCMD5_S32
        #undef PCMD5_S33
        #undef PCMD5_S34
        #undef PCMD5_S41
        #undef PCMD5_S42
        #undef PCMD5_S43
        #undef PCMD5_S44
        #undef PCMD5F 
        #undef PCMD5G 
        #undef PCMD5H 
        #undef PCMD5I 
        #undef PCMD5ROTATE_LEFT
        #undef PCMD5FF
        #undef PCMD5GG
        #undef PCMD5HH
        #undef PCMD5II
        //////////////////////////////////////////////////////////////////
    }

    /* Encodes input (unsigned int) into output (unsigned char). Assumes length is
    a multiple of 4.
    */
    void PCMD5_encode(const unsigned int *input, unsigned char *output, size_t length)
    {
        for (size_t i = 0, j = 0; j<length; i++, j += 4)
        {
            output[j] = (unsigned char)(input[i] & 0xff);
            output[j + 1] = (unsigned char)((input[i] >> 8) & 0xff);
            output[j + 2] = (unsigned char)((input[i] >> 16) & 0xff);
            output[j + 3] = (unsigned char)((input[i] >> 24) & 0xff);
        }
    }
    /* Decodes input (unsigned char) into output (unsigned int). Assumes length is
    a multiple of 4.
    */
    void PCMD5_decode(const unsigned char *input, unsigned int *output, size_t length)
    {
        for (size_t i = 0, j = 0; j<length; i++, j += 4)
        {
            output[i] = ((unsigned int)input[j]) | (((unsigned int)input[j + 1]) << 8) |
                (((unsigned int)input[j + 2]) << 16) | (((unsigned int)input[j + 3]) << 24);
        }
    }
private:
    unsigned int  _state[4];    /* state (ABCD) */
    unsigned int  _count[2];    /* number of bits, modulo 2^64 (low-order word first) */
    unsigned char _buffer[64];  /* input buffer */


};


#endif    //___PCLIB_S_MD5___